package org.budo.ehcache.replicator;

import java.io.Serializable;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 * 缓存同步通知消息
 * 
 * @author lmw
 */
@Slf4j
@Getter
@Setter
@NoArgsConstructor
@ToString
public class ReplicatorMessage implements Serializable {
    private static final long serialVersionUID = -7333854530591931187L;

    private String event;

    private String cacheName;

    private String elementKey;

    public ReplicatorMessage(String event, String cacheName, String elementKey) {
        this.setEvent(event);
        this.setCacheName(cacheName);
        this.setElementKey(elementKey);
    }

    /**
     * build replicatorMessage
     */
    public static ReplicatorMessage newMessage(Ehcache cache, Element element, String event) {
        String cacheName = cache.getName();

        Object elementKey = null == element ? null : element.getObjectKey(); // notifyRemoveAll 事件没有特定 element
        String elementKeyStr = null;

        if (null == elementKey) {
            // elementKeyStr = null;
        } else if (elementKey instanceof String) { // 只支持string类型的key，@see #onRedisMessage(EhcacheRedisReplicatorEventMessage)
            elementKeyStr = (String) elementKey;
        } else {
            log.warn("#90 Cache.Element.Key should be String, cacheName=" + cacheName + ", elementKey=" + elementKey + ", event=" + event);
            elementKeyStr = elementKey.toString();
        }

        ReplicatorMessage message = new ReplicatorMessage(event, //
                cacheName, //
                elementKeyStr);
        return message;
    }
}